import { cuesAttachmentPreview } from '@/services/api/api-cues-attachment';
import { getCuesSubmitDetails } from '@/services/api/api-cues-submit';
import { DownloadOutlined } from '@ant-design/icons';
import { DrawerForm } from '@ant-design/pro-form';
import {
  Alert,
  Avatar,
  Button,
  Card,
  Descriptions,
  // Descriptions,
  Divider,
  Image,
  message,
  Space,
  Spin,
  Tag,
  Typography,
  Upload,
  UploadFile,
} from 'antd';
import moment from 'moment';
import React, { useEffect, useRef, useState } from 'react';
import { useAccess } from 'umi';

interface DetailsSubmitProps {
  item: CuesSubmitData.SubmitPage;
  id: string | undefined;
  name: string | undefined;
  onRefurbish: () => void;
  triggerMode: 'card' | 'title';
}

const DetailsSubmit: React.FC<DetailsSubmitProps> = ({ id, name, onRefurbish, item, triggerMode }) => {
  const access = useAccess();

  const [details, setDetailsState] = useState<CuesSubmitData.SubmitDetails>();

  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewData, setPreviewData] = useState<{
    id: string;
    name: string;
    mimeType: string;
    url?: string;
  }>();
  const [previewOnlineUrl, setPreviewOnlineUrl] = useState<string>();
  const [previewLoading, setPreviewLoading] = useState(true);

  const getWindowSize = () => ({
    innerHeight: window.innerHeight,
    innerWidth: window.innerWidth,
  });
  const [windowSize, setWindowSize] = useState(getWindowSize());
  const handleResize = () => {
    setWindowSize(getWindowSize());
  };
  useEffect(() => {
    // 监听
    window.addEventListener('resize', handleResize);
    // 销毁
    return () => window.removeEventListener('resize', handleResize);
  });

  const iframeRef = useRef(null);

  const handleLoad = () => {
    setPreviewLoading(false);
  };
  useEffect(() => {
    const iframe = iframeRef.current;
    iframe?.addEventListener('load', handleLoad);
    return () => {
      iframe?.removeEventListener('load', handleLoad);
    };
  }, [previewOnlineUrl]);

  /**
   * 获取 详情
   * @param key
   */
  const getSubmitDetails = async () => {
    try {
      const response = await getCuesSubmitDetails({ id });
      if (response.code === 0) {
        setDetailsState(response.data);
      }
    } catch (error) { }
  };
  let recordActions: React.JSX.Element[] | React.ReactNode[] | undefined = [];
  return (
    <DrawerForm
      key="details_details_drawer_form"
      title={<div style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: '80vw' }}>{details?.articleName}</div>}
      drawerProps={{
        // maskClosable: false,
        destroyOnClose: true,
        width: '100%',
      }}
      trigger={
        triggerMode === 'card' ? (
          <div
            style={{
              paddingLeft: 10,
              paddingRight: 10,
              paddingBottom: 10,
            }}
          >
            <Card
              bordered={false}
              hoverable
              style={{

                background: 'linear-gradient(#F5FBFF,#fff, #fff)',
              }}
              actions={recordActions}
            >
              <Card.Meta
                avatar={
                  <Avatar
                    style={{
                      marginTop: '2px',
                    }}
                    size={'large'}
                    src={item.articleOrganizationAvatar}
                  />
                }
                title={
                  <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                    <div
                      style={{
                        whiteSpace: 'nowrap',
                        overflow: 'hidden',
                        textOverflow: 'ellipsis',
                        minWidth: 65,
                      }}
                    >
                      {item.articleOrganizationName}-{item.articleAccountName}
                    </div>
                    <div
                      style={{
                        float: 'right',
                      }}
                    >
                    </div>
                  </div>
                }
                description={
                  <div >
                    <Typography.Paragraph ellipsis={true}>
                      {
                        <span
                          style={{
                            color: '#888A8C',
                            fontSize: 15,
                          }}
                        >
                          {item.articleName}
                        </span>
                      }
                    </Typography.Paragraph>
                    {/* <div>
                      行业：
                      <Space size={[0, 8]} wrap>
                        {item.articleIndustrys?.map((item) => (
                          <Tag key={item.value}>{item.label}</Tag>
                        ))}
                      </Space>
                    </div> */}

                    <div
                      style={{
                        marginTop: 5,
                      }}
                    >
                      标签：
                      <Space size={[0, 8]} wrap>
                        {item.articleLabels.slice(0, 1).map((item, index) => (
                          <Tag key={index}>
                            <div
                              style={{
                                whiteSpace: 'nowrap',
                                overflow: 'hidden',
                                textOverflow: 'ellipsis',
                                maxWidth: 120,
                              }}
                            >
                              {item.label}
                            </div>
                          </Tag>
                        ))}
                        {item.articleLabels.length > 1 ? '...' : ''}
                      </Space>
                    </div>
                    <div style={{ display: 'flex', padding: 0 }}>
                      <span>选题计划：</span>
                      <Typography.Paragraph ellipsis={true}>
                        {
                          <span
                            style={{
                              color: '#888A8C',
                            }}
                          >
                            {item.topicName}
                          </span>
                        }
                      </Typography.Paragraph>
                    </div>
                    <div
                      style={{
                        marginTop: -15,
                        marginRight: 18,
                        display: 'flex',
                        justifyContent: 'space-between',
                        width: '100%'
                      }}
                    >
                      <span
                        style={{
                          float: 'left',
                        }}
                      >
                        联络人:{item.articleAccountName}
                      </span>
                      <span
                        style={{
                          float: 'right',
                        }}
                      >
                        {moment(item.createdTime).fromNow()}
                      </span>
                    </div>
                  </div>
                }
              />
            </Card>
            <div
              style={{
                borderRadius: 12,
                background: '#FFF',
              }}
            >
            </div>
          </div>
        ) : (
          <a>{name}</a>
        )
      }
      onVisibleChange={(visible) => {
        if (visible) {
          getSubmitDetails();
        } else {
          onRefurbish();
        }
      }}
      submitter={false}
    >
      <Spin
        style={{
          textAlign: 'center',
        }}
        spinning={details === undefined}
      >
        <Descriptions>
          <Descriptions.Item label="报送单位">{details?.articleOrganizationName}</Descriptions.Item>
          <Descriptions.Item label="报送人">{details?.articleAccountName}</Descriptions.Item>
          <Descriptions.Item label="联系方式">{details?.articleAccountPhone}</Descriptions.Item>
          <Descriptions.Item label="报送时间">{details?.createdTime}</Descriptions.Item>
        </Descriptions>
        <Descriptions>
          <Descriptions.Item label="选题计划">
            {details?.topicName}
          </Descriptions.Item>
        </Descriptions>
        <Descriptions>
          <Descriptions.Item label="行业">
            <Space size={[0, 8]} wrap>
              {details?.articleIndustrys?.map((item) => {
                return <Tag key={item.value}>{item.label}</Tag>;
              })}
            </Space>
          </Descriptions.Item>
        </Descriptions>

        <Descriptions>
          <Descriptions.Item label="标签">
            {details?.articleLabels.map((item) => {
              return <Tag key={item.value}>{item.label}</Tag>;
            })}
          </Descriptions.Item>
        </Descriptions>
        {/* {details?.articleLabels && details?.articleLabels.length > 0 && (
          <div style={{ marginTop: -5, lineHeight: 2 }}>
            <span
              style={{ color: 'black', marginRight: 10, fontSize: 14, }}
            >
              标签:
            </span>
            {details?.articleLabels.map((item) => {
              return <Tag key={item.value}> {item.label}</Tag>;
            })}
          </div>
        )} */}
        {details?.remarks && (
          <Descriptions layout="vertical">
            <Descriptions.Item label="备注">{details?.remarks}</Descriptions.Item>
          </Descriptions>
        )}
        <Divider />
        {details?.articleName ? (
          <Typography.Title level={3} style={{ textAlign: 'center' }}>
            {details?.articleName}
          </Typography.Title>
        ) : (
          <></>
        )}
        <br />
        {details?.articleContent ? (
          <div
            dangerouslySetInnerHTML={{
              __html: `${details?.articleContent}`,
            }}
          />
        ) : (
          <></>
        )}
        {details?.articleAttachments && details?.articleAttachments.length > 0 && (
          <>
            <Divider />
            <div
              style={{
                textAlign: 'right',
              }}
            >
              <Button
                type="primary"
                key="import"
                size="small"
                icon={<DownloadOutlined />}
                onClick={() => {
                  details?.articleAttachments.forEach(function (item) {
                    window.open(item.content, '_blank');
                  });
                }}
              >
                全部下载
              </Button>
            </div>

            <Upload
              listType="picture"
              multiple
              fileList={details?.articleAttachments.map((item) => {
                return {
                  uid: item.id,
                  name: item.name,
                  url: item.content,
                  mimeType: item.mimeType,
                  status: 'done',
                };
              })}
              showUploadList={{
                downloadIcon: (
                  <div style={{ marginLeft: '-100px', padding: '17px 0', marginTop: '-15px' }}>
                    <DownloadOutlined
                      style={{
                        marginRight: '10px',
                      }}
                    />
                    点击下载
                  </div>
                ),
                showRemoveIcon: false,
                showDownloadIcon: true,
              }}
              onPreview={async (file: UploadFile) => {
                setPreviewData({
                  id: file.uid,
                  name: file.name,
                  mimeType: file.mimeType,
                  url: file.url,
                });
                setPreviewOpen(true);
              }}
            />
            <DrawerForm
              title={previewData?.name}
              drawerProps={{
                width: '100%',
                destroyOnClose: true,
              }}
              visible={previewOpen}
              onVisibleChange={async (visible) => {
                if (visible) {
                  if (
                    previewData?.mimeType !== null &&
                    previewData?.mimeType?.indexOf('image') > -1
                  ) {
                    //图片预览
                  } else {
                    setPreviewLoading(true);

                    const response = await cuesAttachmentPreview({
                      id: previewData?.id,
                    });

                    if (response.code === 0) {
                      setPreviewOnlineUrl(response.data);
                    } else {
                      message.error('暂时无法预览');
                      setPreviewLoading(false);
                    }
                  }
                } else {
                  setPreviewOpen(false);
                  setPreviewData(undefined);
                  setPreviewOnlineUrl(undefined);
                }
              }}
              submitter={{
                searchConfig: {
                  submitText: '下载',
                },
              }}
              onFinish={async (values) => {
                window.open(previewData?.url, '_blank');
              }}
            >
              <Alert
                style={{
                  marginBottom: 20,
                }}
                message="部分文件系统可能暂不支持在线预览，建议下载到本地"
                type="warning"
                showIcon
              />
              {previewData?.mimeType !== null && previewData?.mimeType?.indexOf('image') > -1 ? (
                <Image width="100%" src={previewData?.url} />
              ) : (
                <Spin spinning={previewLoading}>
                  <iframe
                    ref={iframeRef}
                    src={previewOnlineUrl}
                    height={windowSize.innerHeight - 220}
                    width="100%"
                    frameBorder="0"
                    // scrolling="false"
                    allowFullScreen={true}
                  // scrolling={'no'}
                  />
                </Spin>
              )}
            </DrawerForm>
          </>
        )}
      </Spin>
    </DrawerForm>
  );
};

export default DetailsSubmit;
